﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;
using Keepo.Models;
using System.IO;
using Keepo.Helpers;
using Keepo.Models.Services;

namespace Keepo.Designer.Controllers
{
    public class FileSystemController : Controller
    {
        public ActionResult Index()
        {
            return Content("test");
        }

        public ActionResult UploadImage(HttpPostedFileBase[] Filedata)
        {
            string path = "resources/img/";

            var File = Filedata[0];
            string guid = Guid.NewGuid().ToString();

            string filename = Path.GetFileName(File.FileName);
            string ext = Path.GetExtension(filename);
            string newFileName = path + guid + ext;
           
            // Save the image first
            File.SaveAs(Server.MapPath("~/") + newFileName);

            return Json(new { status = true, 
                Filename = newFileName });

        }

        public ActionResult SaveToServer(string filename = "")
        {
            if (filename != "")
            {
                var directory = Path.GetDirectoryName(Server.MapPath("~/") + filename);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                FileStream fs = System.IO.File.Create(Server.MapPath("~/") + filename);
                Request.InputStream.CopyTo(fs);
                fs.Close();
            }

            return Content("ok");
        }

        [HttpPost]
        public ActionResult ImportImageFromUrl(string url = "")
        {
            // RETURNS html to flash IoError
            // HTTPStatusEvent.HTTP_STATUS returns 500
            // throw new Exception("msg");

            // HTTPStatusEvent.HTTP_STATUS, returns 404
            // return new HttpUnauthorizedResult("msg");

            // TBD: convert to post
            // In AS look at URLRequest properties
            var designImage = ImportHelper.ImportImageFromUrl(url);
            
            if (designImage == null)
            {
                return Json(false);
            }
            else
            {
                var export = new DesignImageExport(designImage);
                return Json(export);
            }
        }
    }
}
